//
//  Map.cpp
//  trail-map-editor
//
//  Created by Tino Giorgio on 12/3/13.
//
//

#include "ui.h"

#include "Defines.h"
#include "Map.h"
#include "Sector.h"

using namespace tinyxml2;

//
// Factory static method
//
Map* Map::loadFromXML(const char* filename)
{
	if(!filename)
	{
		ulSetError(UL_FATAL, "NULL view file specified.",filename);
		return 0;
	}
    
    Log.write(PlainText, "Load map from file : %s", filename);
	
	XMLDocument doc;
	XMLError error = doc.LoadFile(filename);
	if(error)
	{
		ulSetError(UL_FATAL, "Map file not found : %s.",filename);
		return 0;
	}
	
	//
	// Look for the 'map' node.
	//
	XMLElement* mapElement = doc.FirstChildElement( "map" );
    
    if(!mapElement)
	{
		ulSetError ( UL_FATAL, "Cannot find map element in %s. map must be the root element!", filename ) ;
		return 0;
	}
    
	const char* name = mapElement->Attribute("name");
	
	Map* map = new Map(name);
	
	_parseSectors(mapElement->FirstChildElement(NULL), map);
	
	return map;
}

void Map::_parseSectors(const XMLElement* element, Map* map)
{
	const XMLElement* sibling = element;
	
	while(sibling)
	{
		const char* name = sibling->Attribute("name");
		int nRows = sibling->IntAttribute("nRows");
		int nCols = sibling->IntAttribute("nCols");
		int east = sibling->IntAttribute("east");
		int north = sibling->IntAttribute("north");
		float avg = sibling->FloatAttribute("avg");
		
		map->mSectors->addEntity(ulStrDup(name));
		
		sibling = sibling->NextSiblingElement();
	}
}

//
// Private constructor
//
Map::Map(const char* name)
: mSectors(new ulList())
{
	mName = ulStrDup(name);
}

Map::~Map()
{
	SAFE_DELETE_STRING(mName);
	
	if(mSectors)
	{
		for(int i = 0; i < mSectors->getNumEntities(); i++)
		{
			char* entity = (char*)mSectors->getEntity(i);
            
            SAFE_DELETE_STRING(entity);
		}
		
		SAFE_DELETE(mSectors);
	}
}
